import json
import random
import time
import string
import os
from datetime import datetime, timedelta

def generate_random_hex(length=6):
    """生成随机十六进制字符串"""
    return ''.join(random.choices('0123456789abcdef', k=length))

def generate_random_base64(length=20):
    """生成类base64随机字符串"""
    chars = string.ascii_letters + string.digits + '+/='
    return ''.join(random.choices(chars, k=length))

def generate_random_number(length=10):
    """生成随机数字字符串"""
    return ''.join(random.choices(string.digits, k=length))

def generate_random_cookie():
    """生成随机微博Cookie"""
    
    # 生成时间戳相关
    current_time = int(time.time())
    expire_time = current_time + random.randint(86400, 2592000)  # 1天到30天
    
    # 构建随机Cookie
    cookie = {
        # 基础标识Cookie
        "_T_WM": generate_random_hex(10),
        "MLOGIN": str(random.randint(0, 1)),
        "WEIBOCN_FROM": "1110006030",
        
        # 认证相关Cookie
        "SUB": f"_2A25{generate_random_hex(8)}f8NxqwFRm{generate_random_hex(32)}",
        "SUBP": f"0033WrSXqPxfM72-Ws9jqgMF55529P9D9W{generate_random_base64(20)}",
        
        # 令牌相关
        "XSRF-TOKEN": generate_random_hex(6),
        "mweibo_short_token": generate_random_hex(10),
        
        # 其他参数
        "M_WEIBOCN_PARAMS": f"luicode%3D10000011%26lfid%3D107603{generate_random_number(10)}%26fid%3D100505{generate_random_number(10)}%26uicode%3D10000011",
        
        # 可选添加的字段
        "ALF": str(expire_time),
        "SSOLoginState": str(current_time),
        
        # 安全相关字段（模拟格式）
        "SCF": f"A{generate_random_base64(50)}.",
        
        # 会话相关
        "WBPSESS": f"{generate_random_base64(80)}=="
    }
    
    return cookie

def save_cookie_to_file(cookie, filename=None):
    """保存Cookie到文件"""
    if filename is None:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"weibo_cookies_{timestamp}.json"
        filename = f"weibo_cookies.json"
    # 确保目录存在
    os.makedirs("cookies", exist_ok=True)
    filepath = os.path.join("cookies", filename)
    filepath = os.path.join("./", filename)
    
    try:
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(cookie, f, ensure_ascii=False, indent=4)
        print(f"✅ Cookie已保存到: {filepath}")
        return filepath
    except Exception as e:
        print(f"❌ 保存Cookie失败: {e}")
        return None

def generate_multiple_cookies(count=5):
    """生成多个随机Cookie"""
    cookies = {}
    for i in range(count):
        cookie_name = f"cookie_{i+1}"
        cookies[cookie_name] = generate_random_cookie()
    
    # 保存到单个文件
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"weibo_cookies.json"

    
    try:
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(cookies, f, ensure_ascii=False, indent=4)
        print(f"✅ 共生成 {count} 个Cookie，已保存到: {filename}")
        return filename
    except Exception as e:
        print(f"❌ 保存多个Cookie失败: {e}")
        return None

def validate_cookie_format(cookie):
    """验证Cookie格式"""
    required_fields = ['_T_WM', 'SUB', 'SUBP', 'XSRF-TOKEN']
    
    for field in required_fields:
        if field not in cookie:
            return False, f"缺少必要字段: {field}"
        
        if not cookie[field] or len(str(cookie[field])) < 2:
            return False, f"字段 {field} 的值无效"
    
    return True, "Cookie格式验证通过"

def main():
    """主函数"""
    print("=== 微博随机Cookie生成器 ===")
    
    while True:
        print("\n请选择操作:")
        print("1. 生成单个随机Cookie")
        print("2. 生成多个随机Cookie")
        print("3. 退出")
        
        choice = 1
        
        if choice == '1':
            # 生成单个Cookie
            print("\n正在生成随机Cookie...")
            cookie = generate_random_cookie()
            
            # 验证格式
            is_valid, message = validate_cookie_format(cookie)
            if is_valid:
                print("✅ Cookie格式验证通过")
                
                # 显示Cookie信息
                print("\n生成的Cookie:")
                for key, value in cookie.items():
                    print(f"  {key}: {value[:50]}{'...' if len(str(value)) > 50 else ''}")
                
                # 保存到文件
                save_choice = input("\n是否保存到文件? (y/n): ").strip().lower()
                if save_choice in ['y', 'yes']:
                    filename = input("请输入文件名 (留空使用默认名称): ").strip()
                    if not filename:
                        filename = None
                    save_cookie_to_file(cookie, filename)
                else:
                    print("❌ 未保存Cookie")
            else:
                print(f"❌ {message}")
                
        elif choice == '2':
            # 生成多个Cookie
            try:
                count = int(input("请输入要生成的Cookie数量: "))
                if count <= 0:
                    print("❌ 数量必须大于0")
                    continue
                
                if count > 100:
                    print("⚠️  数量较多，生成可能需要一些时间...")
                
                generate_multiple_cookies(count)
                
            except ValueError:
                print("❌ 请输入有效的数字")
                
        elif choice == '3':
            print("👋 退出程序")
            break
            
        else:
            print("❌ 无效选择，请重新输入")

# 快速生成函数
def quick_generate_cookie444():
    """快速生成一个Cookie并保存"""
    cookie = generate_random_cookie()
    filename = save_cookie_to_file(cookie)
    return cookie, filename

def quick_generate_multiple(count=3):
    """快速生成多个Cookie"""
    return generate_multiple_cookies(count)

# if __name__ == "__main__":
    # 可以直接运行主程序
    #main()
    
    # 或者使用快速函数
    # cookie, filename = quick_generate_cookie()
    # print(f"快速生成Cookie: {filename}")